package com.twenty.seven.webapp.demo.aop;

import com.twenty.seven.entity.TripartiteEntity;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Aspect
@Order(1)
@Component
public class TripartitePlatformSecurity {

    private static final Logger logger = LoggerFactory.getLogger(TripartitePlatformSecurity.class);

    ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Pointcut("execution(public * com.twenty.seven.webapp.demo.controller.TripartitePlatformDemo.*(..)) && args(entity,..)")
    public void pointTripartitePlatform(TripartiteEntity entity){}

    @Before("pointTripartitePlatform(entity)")
    public void runBefore(JoinPoint joinPoint,TripartiteEntity entity){

        preMsy(joinPoint);
        //业务部分，可以校验前签名使用
        System.out.println("这是Aspect 切片……");
        //先判断必要的参数
        entity.setReturnCode(200);
    }

    @AfterReturning(returning = "response", pointcut = "pointTripartitePlatform(entity)")
    public void runAfterReturning(Object response,TripartiteEntity entity) {
        logger.info(">>>SPEND TIME : {}", (System.currentTimeMillis() - startTime.get()) + "ms");
    }

    private void preMsy(JoinPoint joinPoint){
        startTime.set(System.currentTimeMillis());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        logger.info(">>>>>>第三方接口请求校验开始");
        logger.info(">>>>>>请求来源信息");
        logger.info(">>>URL : {}", request.getRequestURL()+" ["+request.getMethod()+"]");
        logger.info(">>>IP : {}", request.getRemoteAddr());
        Enumeration<String> headerNames = request.getHeaderNames();
//        while(headerNames.hasMoreElements()) {
//            String nextElement = headerNames.nextElement();
//            logger.info(">>>"+nextElement.toUpperCase() + " : {}", request.getHeader(nextElement));
//        }
        logger.info(">>>CLASS_METHOD : {}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
//        logger.info(">>>PARAM : {}", null != request.getQueryString() ? JSON.toJSONString(request.getQueryString().split("&")) : "EMPTY");
//        logger.info(">>>POST PARAM:"+ JSONObject.toJSONString(joinPoint.getArgs()));

    }
}
